package com.cskaoyan.servlet;

import com.cskaoyan.bean.BrandListParameter;
import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.model.MarketBrand;
import com.cskaoyan.service.BrandService;
import com.cskaoyan.service.impl.BrandServiceImpl;
import com.cskaoyan.utils.JacksonUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;


@WebServlet("/admin/brand/*")
public class AdminBrandServlet extends CommonServlet {

    BrandService brandService = new BrandServiceImpl();

    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException {
        request.setCharacterEncoding("utf-8");
        Map<String, String[]> map = request.getParameterMap();
        BrandListParameter parameter = new BrandListParameter();
        BeanUtils.copyProperties(parameter,map);
        List<MarketBrand> marketBrands = brandService.list(parameter);
        PageData data = PageData.list(marketBrands);
        return BaseRespVo.ok(data);
    }

    public BaseRespVo create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        String jsonStr = request.getReader().readLine();
        MarketBrand marketBrand = JacksonUtil.read(jsonStr, MarketBrand.class);
        MarketBrand marketBrand1 = brandService.create(marketBrand);
        return BaseRespVo.ok(marketBrand1);
    }

    public BaseRespVo update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        String jsonStr = request.getReader().readLine();
        MarketBrand marketBrand = JacksonUtil.read(jsonStr, MarketBrand.class);
        MarketBrand marketBrand1 = brandService.update(marketBrand);
        return BaseRespVo.ok(marketBrand1);
    }

    public BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        String jsonStr = request.getReader().readLine();
        MarketBrand marketBrand = JacksonUtil.read(jsonStr, MarketBrand.class);
        brandService.delete(marketBrand);
        return BaseRespVo.ok(null);
    }
}
